//
//  SportsMessage.m
//  uteped_sdk
//
//  Created by mateng on 2024/2/20.
//

#import "SportsMessage.h"
#import "UTEPedMethodCallHandler.h"

#define PATH                      @"sports"

@implementation SportsMessage

- (id)initWithHandler:(UTEPedEventHandler *)handler {
    self = [super initWithHandler:handler];
    if (self) {
        [LocationHelper shareInstance].delegate = self;
    }
    return self;
}

- (NSString *)getPath {
    return PATH;
}

# pragma mark - sports notification listen
- (void)notificationListen {
    __weak typeof(self)weakSelf = self;
    
    // 通过operatorType同步设备的开始、暂停、继续、结束
    [[UTEDeviceMgr sharedInstance] onNotifyDeviceOperator:^(UTEModelDeviceOperator *model, NSDictionary *uteDict) {
        NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
                              PATH, KEY_PATH,
                              M_setDeviceOperator, KEY_METHOD,
                              [uteDict valueForKey:@"data"], KEY_VALUE, nil];

        [self.eventHander publishEvent:data async:YES];
    }];
    
    // 监听上报单次运动结束记录统计值信息 通知事件ID 为固定的 5897
    [[UTEDeviceMgr sharedInstance] onNotifySportOneRecord:^(UTEModelDeviceSportOneRecord *model, NSDictionary *uteDict) {
        NSDictionary *data = [NSDictionary dictionaryWithObjectsAndKeys: PATH, KEY_PATH, M_setSportOneRecord, KEY_METHOD, [uteDict valueForKey:@"data"], KEY_VALUE, nil];
        
        [self.eventHander publishEvent:data async:YES];
    }];
    
    // 运动中实时上报数据，结合23.11选择需求数据下发给设备
    [[UTEDeviceMgr sharedInstance] onNotifySportRealData:^(UTEModelDeviceSportRealData *model, NSDictionary *uteDict) {
        NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
                              PATH, KEY_PATH,
                              M_setWorkoutRealTimeData, KEY_METHOD,
                              [uteDict valueForKey:@"data"], KEY_VALUE, nil];
        
        [weakSelf.eventHander publishEvent:data async:YES];
    }];
    
    // 24.2 监听手环请求GPS参数数据 通知事件ID 为固定的 6146
    [[UTEDeviceMgr sharedInstance] onNotifyGPS:^(NSDictionary *uteDict) {
        
        NSNumber *enable = [[uteDict objectForKey:@"data"] valueForKey: @"enable"];
                
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                              @(enable.boolValue), @"isGpsEnable", nil];
        
        NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
                              PATH, KEY_PATH,
                              M_setGpsParams, KEY_METHOD,
                              dict, KEY_VALUE, nil];
        
        [weakSelf.eventHander publishEvent:data async:YES];
    }];
    
    // 监听设备主动修改当前运动列表变化
    [[UTEDeviceMgr sharedInstance] onNotifySportDisplay:^(NSArray<NSNumber *> *array) {
        NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys: array, TYPE_LIST, nil];
        
        NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
                              PATH, KEY_PATH,
                              M_queryWorkOutManageInfo, KEY_METHOD,
                              dict, KEY_VALUE, nil];
        
        [weakSelf.eventHander publishEvent:data async:YES];
    }];
    
    // 当在设备端健康数据、运动数据有更新时，会通知APP端
    [[UTEDeviceMgr sharedInstance] onNotifySportData:^(NSInteger type, NSDictionary *uteDict) {
//        NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
//                              @"home", KEY_PATH,
//                              @"localNotify", KEY_METHOD,
//                              @"ACTION_SYNC_DATA_COMPLETE", KEY_ACTION, nil];
//        [weakSelf.eventHander publishEvent:data async:YES];
        [[UTEPedMethodCallHandler shareInstance] publishLocal:ACTION_SPORT_DATA_NOTIFY value:@""];
    }];
}

- (void)onSignalLevelChanged:(NSInteger)level {
    __weak typeof(self)weakSelf = self;
    
    NSDictionary *dict = [[NSDictionary alloc] initWithObjectsAndKeys:
                          @(level), @"signal", nil];
    
    NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
                          PATH, KEY_PATH,
                          M_startGpsSignal, KEY_METHOD,
                          dict, KEY_VALUE, nil];
    
    [weakSelf.eventHander publishEvent:data async:YES];
}

# pragma mark - methodCallConsumed
- (BOOL) methodCallConsumed:(NSString*)method params:(NSDictionary*)params result:(FlutterResult)result
{
    BOOL consumed = YES;
    if ([super methodCallConsumed:method params:params result:result])
        return YES;
    
    assert(method != nil);

    __weak typeof(self)weakSelf = self;
    
    if ([method isEqualToString: M_queryWorkOutManageInfo]) { // 获取运动管理等信息
        if (![self isConnected]) {
            result([NSDictionary dictionary]);
            return YES;
        }
        
        [[UTEDeviceMgr sharedInstance] readSportMangerInfo:^(UTEModelSportMangerInfo *model, NSInteger errorCode) {
            if (errorCode == UTEDeviceErrorNil) {
                NSDictionary *data = [[NSDictionary alloc] initWithObjectsAndKeys:
                      @(model.supportMax), @"maxCount",
                      @(model.supportMin), @"minCount",
                      model.numSupportType, @"supportsSportsList",
                      model.numCurrent, @"addedSportsList", nil];
                result(data);
            } else {
                result([NSDictionary dictionary]);
            }
        }];
    } else if ([method isEqualToString: M_setSportDisplay]) { // 设置当前手环显示的运动种类列表
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSArray *arr = [params objectForKey:TYPE_LIST];
        [[UTEDeviceMgr sharedInstance] setSportDisplay:arr block:^(NSInteger errorCode) {
            result(@([weakSelf isSuccess:errorCode]));
        }];
    } else if ([method isEqualToString: M_setCurrentGPSModel]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        UTEModeCurrentGPS *gps = [UTEModeCurrentGPS new];
        NSDictionary *map = [params objectForKey:TYPE_MAP];
        gps.gpsLatitude = [[map objectForKey:@"gpsLatitude"] doubleValue];
        gps.gpsLongitude = [[map objectForKey:@"gpsLongitude"] doubleValue];
        gps.timeStamp = [[map objectForKey:@"timeStamp"] intValue];
        
        [[UTEDeviceMgr sharedInstance] setCurrentGPSModel:gps block:^(NSInteger errorCode) {
            result(@([weakSelf isSuccess:errorCode]));
        }];
    } else if ([method isEqualToString: M_setGpsParams]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        UTEModeGpsParam *gps = [weakSelf getGpsParams:params];
        // 运动中GPS实时下发
        [[UTEDeviceMgr sharedInstance] setGpsParamsModel:gps block:^(NSInteger errorCode, NSDictionary *uteDict) {
            result(@([weakSelf isSuccess:errorCode]));
        }];
    } else if ([method isEqualToString: M_setWorkoutRealTimeData]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        UTEModeSportWorkoutRealTimeData *data = [weakSelf getWorkoutRealTimeData:params];
        // 23.11 设置联动运动实时数据 运动中根据需要字段实时调用下发给手环
        [[UTEDeviceMgr sharedInstance] setWorkoutRealTimeDataModel:data block:^(NSInteger errorCode, NSDictionary *uteDict) {
            result(@([weakSelf isSuccess:errorCode]));
        }];
    } else if ([method isEqualToString: M_setIsOpenWorkoutOperatorReport]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        NSNumber *enable = @(YES);
        if ([params objectForKey:KEY_ENABLE]) {
            enable = [params objectForKey:KEY_ENABLE];
        }
        NSLog(@"M_setIsOpenWorkoutOperatorReport %d", [enable intValue]);
        [[UTEDeviceMgr sharedInstance] setIsOpenWorkoutOperatorReport:[enable boolValue] block:^(NSInteger errorCode, NSDictionary *uteDict) {
            result(@([weakSelf isSuccess:errorCode]));
        }];
    } else if ([method isEqualToString: M_getDeviceOperatorState]) {
        if (![self isConnected]) {
            result([NSDictionary dictionary]);
            return YES;
        }
        
        [[UTEDeviceMgr sharedInstance] getDeviceOperatorState:^(UTEModelDeviceOperatorState *model, NSInteger errorCode, NSDictionary *uteDict) {
            if (errorCode == UTEDeviceErrorNil) {
                result([uteDict objectForKey:@"data"]);
            } else {
                result([NSDictionary dictionary]);
            }
        }];
    } else if ([method isEqualToString: M_setDeviceOperator]) {
        if (![self isConnected]) {
            result(@NO);
            return YES;
        }
        
        UTEModelDeviceOperator *operator = [weakSelf getOperator:params];
        [[UTEDeviceMgr sharedInstance] setDeviceOperatorModel:operator block:^(NSInteger errorCode, NSDictionary *uteDict) {
            result(@([weakSelf isSuccess:errorCode]));
        }];
    } else if ([method isEqualToString: M_startGpsSignal]) {
        [[LocationHelper shareInstance] startLocation];
        result(@(YES));
    } else if ([method isEqualToString: M_stopGpsSignal]) {
        [[LocationHelper shareInstance] stopLocation];
        result(@(YES));
    } else {
        consumed = NO;
    }
    
    return consumed;
}

- (UTEModeSportWorkoutRealTimeData*)getWorkoutRealTimeData:(NSDictionary*)params {
    NSDictionary *dict = [params objectForKey:TYPE_MAP];
    UTEModeSportWorkoutRealTimeData *data = [UTEModeSportWorkoutRealTimeData new];
    
    data.operatorType = [[dict objectForKey:@"operator"] intValue];
    
    if ([dict objectForKey:@"workoutDuration"] != NULL && [[dict objectForKey:@"workoutDuration"] class] != [NSNull class]) {
        data.workoutDuration = [[dict objectForKey:@"workoutDuration"] intValue];
    }
    
    if ([dict objectForKey:@"realTimeHeartRate"] != NULL && [[dict objectForKey:@"realTimeHeartRate"] class] != [NSNull class]) {
        data.realTimeHeartRate = [[dict objectForKey:@"realTimeHeartRate"] intValue];
    }
    
    if ([dict objectForKey:@"steps"] != NULL && [[dict objectForKey:@"steps"] class] != [NSNull class]) {
        data.steps = [[dict objectForKey:@"steps"] intValue];
    }
    
    if ([dict objectForKey:@"altitude"] != NULL && [[dict objectForKey:@"altitude"] class] != [NSNull class]) {
        data.altitude = [[dict objectForKey:@"altitude"] intValue];
    }
    
    if ([dict objectForKey:@"distance"] != NULL && [[dict objectForKey:@"distance"] class] != [NSNull class]) {
        data.distance = [[dict objectForKey:@"distance"] intValue];
    }
    
    if ([dict objectForKey:@"calorie"] != NULL && [[dict objectForKey:@"calorie"] class] != [NSNull class]) {
        data.calorie = [[dict objectForKey:@"calorie"] intValue];
    }
    
    if ([dict objectForKey:@"pace"] != NULL && [[dict objectForKey:@"pace"] class] != [NSNull class]) {
        data.pace = [[dict objectForKey:@"pace"] intValue];
    }
    
    if ([dict objectForKey:@"stepCadence"] != NULL && [[dict objectForKey:@"stepCadence"] class] != [NSNull class]) {
        data.stepCadence = [[dict objectForKey:@"stepCadence"] intValue];
    }
    
    return data;
}

- (UTEModelDeviceOperator*)getOperator:(NSDictionary*)params {
    UTEModelDeviceOperator *operator = [UTEModelDeviceOperator new];
    
    NSDictionary *map = [params objectForKey:TYPE_MAP];
    
    operator.operatorType = [[map objectForKey:@"operatorType"] intValue];
    operator.sportType = 1;
    operator.planStartDate = [[map objectForKey:@"startTime"] intValue];
    operator.startTime = [[map objectForKey:@"startTime"] intValue];
    operator.operationTime = [[map objectForKey:@"startTime"] intValue];
    operator.workoutType = [[map objectForKey:@"workoutType"] intValue];
    operator.forbidPause = [[map objectForKey:@"forbidPause"] intValue];
    
        
    UTEModelDeviceTargetInfo *target = [UTEModelDeviceTargetInfo new];
    if ([map objectForKey:@"distance"]) {
        target.distance =[[map objectForKey:@"distance"] intValue];
    }
    if ([map objectForKey:@"calories"]) {
        target.calorie =[[map objectForKey:@"calories"] intValue];
    }
    if ([map objectForKey:@"duration"]) {
        target.duration =[[map objectForKey:@"duration"] intValue];
    }
    
    operator.targetInfo = target;
    
    return operator;
}

- (UTEModeGpsParam*)getGpsParams: (NSDictionary*)params {
    UTEModeGpsParam *gps =  [UTEModeGpsParam new];
    
    NSDictionary *map = [params objectForKey:TYPE_MAP];
    
    gps.gpsLatitude = [[map objectForKey:@"gpsLatitude"] doubleValue];
    gps.gpsLongitude = [[map objectForKey:@"gpsLongitude"] doubleValue];
    gps.altitude = [[map objectForKey:@"altitude"] intValue];
    gps.accuracy = [[map objectForKey:@"accuracy"] doubleValue];
    gps.gcj02Latitude = 0;
    gps.gcj02Longitude = 0;
    return gps;
}

@end
